package com.xxxx.seckill.controller;

import com.xxxx.seckill.VO.DetailVO;
import com.xxxx.seckill.VO.GoodsVO;
import com.xxxx.seckill.VO.ResponseBean;
import com.xxxx.seckill.pojo.User;
import com.xxxx.seckill.service.IGoodsService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring6.view.ThymeleafViewResolver;
import org.thymeleaf.web.IWebExchange;
import org.thymeleaf.web.servlet.JakartaServletWebApplication;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 商品
 */
@Controller
@RequestMapping("/goods")
public class GoodsController {

/*
    @Autowired
    private IUserService userService;
*/

    @Autowired
    private IGoodsService goodsService;

    /**
     * 页面缓存：
     * 首先从 Redis 里面读取缓存
     * 如果有页面，直接返还给浏览器
     * 如果没有页面，就需要手动渲染模板（而非通过 Spring 框架），还要存到 Redis 里面，并且输出浏览器端
     */
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * Thymeleaf 模板引擎：
     * 手动渲染
     */
    @Autowired
    private ThymeleafViewResolver thymeleafViewResolver;

    /**
     * 功能描述：跳转商品列表页
     *
     * @param model:
     * @param user:
     * @return :
     */
    @RequestMapping(value = "/toList", produces = "text/html;charset=utf-8")
    @ResponseBody
    public String toList(Model model, User user, HttpServletRequest request, HttpServletResponse response) {
        // Redis 中获取页面，如果不为空，则直接返回页面
        ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
        String html = (String) valueOperations.get("goodsList");

        // if (StringUtils.isEmpty(html)) // isEmpty已被启用
        if (StringUtils.hasText(html)) { // 如果字符串不为 null ，长度大于 0 ，且不是空白字符，则返回 true，否则返回 false
            return html;
        }

/* 解耦前的写法：
        if (StringUtils.isEmpty(ticket)) {
            return "login";
        }
        // 通过session找到用户信息，引入Redis以后不再将用户信息存入session中，所以不能这么写了
        // User user = (User) session.getAttribute(ticket); // session存储在服务器上，用户那里是看不到的
        User user = userService.getUserByCookie(ticket, request, response);
        if (null == user) {
            return "login";
        }
*/
        model.addAttribute("user", user); // 把用户对象传到前端页面
        model.addAttribute("goodsList", goodsService.findGoodsVO());
        // return "goodsList";

        /*
         * 如果为空，则手动渲染，存入 Redis 并返回
         */

        /*
         * // 写法已经发生了变化
         * WebContext webContext = new WebContext(request, response, request.getServletContext(), request.getLocale(), model.asMap());
         */

        // 创建 JakartaServletWebApplication 对象
        JakartaServletWebApplication application = JakartaServletWebApplication.buildApplication(request.getServletContext());
        // 创建 IWebExchange 对象
        IWebExchange webExchange = application.buildExchange(request, response);
        // 创建 WebContext 对象
        WebContext webContext = new WebContext(webExchange, request.getLocale(), model.asMap());
        // 使用引擎渲染
        html = thymeleafViewResolver.getTemplateEngine().process("goodsList", webContext);
        if (StringUtils.hasText(html)) {
            valueOperations.set("goodsList", html, 60, TimeUnit.SECONDS); // 失效时间为 60s
        }
        return html;
    }

    /**
     * 功能描述：跳转商品详情页面
     * 通过 model 传输数据
     *
     * @param goodsId :
     * @return :
     */
    @RequestMapping(value = "/toDetail/{goodsId}", produces = "text/html;charset=utf-8")
    @ResponseBody
    public String toDetail(Model model, User user, @PathVariable Long goodsId, HttpServletRequest request, HttpServletResponse response) {
        ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
        // Redis 中获取页面，如果不为空，则直接返回页面
        String html = (String) valueOperations.get("goodsDetail:" + goodsId);
        if (StringUtils.hasText(html)) {
            return html;
        }
        model.addAttribute("user", user);
        GoodsVO goodsVO = goodsService.findGoodsVOByGoodsId(goodsId);
        Date startTime = goodsVO.getStartTime();
        Date endTime = goodsVO.getEndTime();
        Date nowTime = new Date();

        int seckillStatus; // 秒杀状态
        int remainingSeconds; // 秒杀倒计时
        if (nowTime.before(startTime)) { // 秒杀还未开始
            seckillStatus = 0;
            remainingSeconds = (int) (startTime.getTime() - nowTime.getTime()) / 1000;
        } else if (nowTime.after(endTime)) { // 秒杀已经结束
            seckillStatus = 2;
            remainingSeconds = -1;
        } else { // 秒杀进行中
            seckillStatus = 1;
            remainingSeconds = 0;
        }
        model.addAttribute("remainingSeconds", remainingSeconds);
        model.addAttribute("seckillStatus", seckillStatus);
        model.addAttribute("goods", goodsVO);
        // return "goodsDetail";

        /*
          如果为空，则手动渲染，存入 Redis 并返回
         */

        // 创建 JakartaServletWebApplication 对象
        JakartaServletWebApplication application = JakartaServletWebApplication.buildApplication(request.getServletContext());
        // 创建 IWebExchange 对象
        IWebExchange webExchange = application.buildExchange(request, response);
        // 创建 WebContext 对象
        WebContext webContext = new WebContext(webExchange, request.getLocale(), model.asMap());
        // 使用引擎渲染
        html = thymeleafViewResolver.getTemplateEngine().process("goodsDetail", webContext);
        if (StringUtils.hasText(html)) {
            valueOperations.set("goodsDetail:" + goodsId, html, 60, TimeUnit.SECONDS); // 失效时间为 60s
        }
        return html;
    }

    /**
     * 功能描述：跳转商品详情页面
     * 前端通过 Ajax 访问接口，再获取数据
     *
     * @param goodsId :
     * @return :
     */
    @RequestMapping("/detail/{goodsId}")
    @ResponseBody
    public ResponseBean detail(User user, @PathVariable Long goodsId) {

        GoodsVO goods = goodsService.findGoodsVOByGoodsId(goodsId);
        Date startTime = goods.getStartTime();
        Date endTime = goods.getEndTime();
        Date nowTime = new Date();

        int seckillStatus; // 秒杀状态
        int remainingSeconds; // 秒杀倒计时
        if (nowTime.before(startTime)) { // 秒杀还未开始
            seckillStatus = 0;
            remainingSeconds = (int) (startTime.getTime() - nowTime.getTime()) / 1000;
        } else if (nowTime.after(endTime)) { // 秒杀已经结束
            seckillStatus = 2;
            remainingSeconds = -1;
        } else { // 秒杀进行中
            seckillStatus = 1;
            remainingSeconds = 0;
        }

        DetailVO detailVO = new DetailVO();
        detailVO.setUser(user);
        detailVO.setGoods(goods);
        detailVO.setSeckillStatus(seckillStatus);
        detailVO.setRemainingSeconds(remainingSeconds);

        return ResponseBean.success(detailVO);
    }
}
